package org.zoomdev.zoom.dao;

import org.zoomdev.zoom.common.utils.Visitor;
import org.zoomdev.zoom.dao.transaction.Transactions;

public final class Db {

    private static final Object lock = new Object();
    public static Dao[] daos = new Dao[100];
    public static int count = 0;

    public static void register(Dao dao) {
        synchronized (lock) {
            daos[count++] = dao;
        }
    }

    /**
     * 对于默认的Dao，可以用这种方式来访问
     *
     * @param type
     * @param <T>
     * @return
     */
    public static <T> EAr<T> ar(Class<T> type) {
        return daos[0].ar(type);
    }

//
//    public static void unregister(Dao dao) {
//        synchronized (lock) {
//            for (int i = 0; i < count; ++i) {
//                if (daos[i] == dao) {
//                    for (int j = i + 1; j < count; ++j) {
//                        daos[j - 1] = daos[j];
//                    }
//                    break;
//                }
//            }
//            daos[--count] = null;
//        }
//    }

    public static void release() {
        visit(Dao::release);
    }

    public static void visit(Visitor<Dao> visitor) {
        Dao[] copyDaos = daos;
        int c = count;
        for (int i = 0; i < c; ++i) {
            Dao dao = copyDaos[i];
            if (dao != null) {
                visitor.visit(dao);
            }
        }
    }

    public static void executeTrans(Runnable runnable) {
        Transactions.executeTrans(runnable);
    }
}
